/*
 * @Author: lei
 * @Description: 正则库的基本使用
 * @FilePath: /9-11/regex.cc
 */
#include <string>
#include <regex>
#include <iostream>

using namespace std;
//g++ -o regex regex.cc -std=c++11

void PrintMatches(string& str,regex reg)//查找与模式匹配的子串
{
    std::smatch matches;
    cout<<boolalpha;
    while(regex_search(str,matches,reg))
    //while(regex_match(str,matches,reg))
    {
        cout<< "matches.ready()= " <<matches.ready()<<endl;
        cout<< "matches.empty()= " <<matches.empty()<<endl;
        cout<< "matches.size()= " <<matches.size()<<endl;

        for(int i=0;i<matches.size();i++)
        {
            cout<< "matches.str("<<i<<")= " <<matches.str(i)<<endl;
        }
        string s2=matches.prefix().str();
        cout<< "matches.prefix().str()= " <<s2<<endl;
        str=matches.suffix().str();
        cout<< "matches.suffix().str()= " <<str<<endl;
        cout<<"------------------------------------"<<endl;
    } 
}
void PrintMatches2(string& str,regex reg)
{
    sregex_iterator current_match(str.begin(),str.end(),reg);
    sregex_iterator last_match;
    while(current_match != last_match)
    {
        smatch match= *current_match;
        cout<< match.str() << endl;
        current_match++;
    }
}
void Replace(string& old_str,regex reg,string& new_sub_str)//替换 匹配部分
{
    cout << "old_str: " << old_str << endl;
    string new_str = regex_replace(old_str,reg,new_sub_str);
    cout << "new_str: " << new_str << endl;
}
//Because regex_match only considers full matches,，
//so the same regex may give different matches between regex_match and std::regex_search:
/*
std::regex re("Get|GetValue");
std::cmatch m;
std::regex_search("GetValue", m, re);  // returns true, and m[0] contains "Get"
std::regex_match ("GetValue", m, re);  // returns true, and m[0] contains "GetValue"
std::regex_search("GetValues", m, re); // returns true, and m[0] contains "Get"
std::regex_match ("GetValues", m, re); // returns false
*/

int main()
{
    string str("the ape was at the apex apecx");
    regex reg("(ape[^ ]?)");
    //string str("GetValues");
    //std::regex reg("Get|GetValue");
    PrintMatches(str,reg);
    //PrintMatches2(str,reg);

    string new_sub_str("666");
    Replace(str,reg,new_sub_str);
    return 0;
}
